package com.ruoyi.module.controller;

import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.module.domain.UserCustomDict;
import com.ruoyi.module.domain.UserCustomDictWord;
import com.ruoyi.module.service.IUserCustomDictService;
import com.ruoyi.module.service.IUserCustomDictWordService;

/**
 * 自定义词典Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/api/custom-dict")
public class CustomDictController extends BaseController
{
    @Autowired
    private IUserCustomDictService userCustomDictService;

    @Autowired
    private IUserCustomDictWordService userCustomDictWordService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 查询用户自定义词典列表
     */
    @GetMapping("/list")
    public TableDataInfo list(UserCustomDict userCustomDict)
    {
        startPage();
        userCustomDict.setUserId(SecurityUtils.getUserId());
        List<UserCustomDict> list = userCustomDictService.selectUserCustomDictList(userCustomDict);
        return getDataTable(list);
    }

    /**
     * 获取自定义词典详情（包含单词列表）
     */
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        UserCustomDict dict = userCustomDictService.selectUserCustomDictById(id);
        if (dict == null) {
            return AjaxResult.error("词典不存在");
        }
        
        // 验证权限
        if (!dict.getUserId().equals(SecurityUtils.getUserId()) && dict.getIsPublic() != 1) {
            return AjaxResult.error("无权访问此词典");
        }
        
        // 查询词典的单词列表
        UserCustomDictWord query = new UserCustomDictWord();
        query.setDictId(id);
        List<UserCustomDictWord> words = userCustomDictWordService.selectUserCustomDictWordList(query);
        dict.setWords(words);
        
        return AjaxResult.success(dict);
    }

    /**
     * 创建自定义词典
     */
    @Log(title = "创建自定义词典", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody JsonNode params)
    {
        try {
            // 生成词典ID
            String dictId = "custom_" + UUID.randomUUID().toString().replace("-", "");
            
            UserCustomDict dict = new UserCustomDict();
            dict.setId(dictId);
            dict.setUserId(SecurityUtils.getUserId());
            dict.setName(params.get("name").asText());
            dict.setDescription(params.has("description") ? params.get("description").asText() : "");
            dict.setCategory(params.has("category") ? params.get("category").asText() : "自定义单词");
            dict.setLanguage(params.has("language") ? params.get("language").asText() : "en");
            dict.setLanguageCategory(params.has("languageCategory") ? params.get("languageCategory").asText() : "en");
            dict.setIsPublic(params.has("isPublic") && params.get("isPublic").asBoolean() ? 1 : 0);
            
            // 处理标签
            if (params.has("tags") && params.get("tags").isArray()) {
                StringBuilder tagsBuilder = new StringBuilder();
                for (JsonNode tag : params.get("tags")) {
                    if (tagsBuilder.length() > 0) {
                        tagsBuilder.append(",");
                    }
                    tagsBuilder.append(tag.asText());
                }
                dict.setTags(tagsBuilder.toString());
            }
            
            // 处理单词列表
            int wordCount = 0;
            if (params.has("words") && params.get("words").isArray()) {
                JsonNode wordsNode = params.get("words");
                wordCount = wordsNode.size();
                
                // 先插入词典
                int result = userCustomDictService.insertUserCustomDict(dict);
                if (result > 0) {
                    // 批量插入单词
                    int sortOrder = 0;
                    for (JsonNode wordNode : wordsNode) {
                        UserCustomDictWord word = new UserCustomDictWord();
                        word.setDictId(dictId);
                        word.setWord(wordNode.get("word").asText());
                        word.setTranslation(wordNode.get("translation").asText());
                        if (wordNode.has("phonetic")) {
                            word.setPhonetic(wordNode.get("phonetic").asText());
                        }
                        if (wordNode.has("example")) {
                            word.setExample(wordNode.get("example").asText());
                        }
                        word.setSortOrder(sortOrder++);
                        userCustomDictWordService.insertUserCustomDictWord(word);
                    }
                }
            } else {
                userCustomDictService.insertUserCustomDict(dict);
            }
            
            // 更新词典的单词数量
            dict.setLength(wordCount);
            userCustomDictService.updateUserCustomDict(dict);
            
            return AjaxResult.success().put("id", dictId);
        } catch (Exception e) {
            logger.error("创建自定义词典失败", e);
            return AjaxResult.error("创建失败: " + e.getMessage());
        }
    }

    /**
     * 修改自定义词典
     */
    @Log(title = "修改自定义词典", businessType = BusinessType.UPDATE)
    @PutMapping("/{id}")
    public AjaxResult edit(@PathVariable String id, @RequestBody JsonNode params)
    {
        try {
            UserCustomDict dict = userCustomDictService.selectUserCustomDictById(id);
            if (dict == null) {
                return AjaxResult.error("词典不存在");
            }
            
            // 验证权限
            if (!dict.getUserId().equals(SecurityUtils.getUserId())) {
                return AjaxResult.error("无权修改此词典");
            }
            
            if (params.has("name")) {
                dict.setName(params.get("name").asText());
            }
            if (params.has("description")) {
                dict.setDescription(params.get("description").asText());
            }
            if (params.has("category")) {
                dict.setCategory(params.get("category").asText());
            }
            if (params.has("isPublic")) {
                dict.setIsPublic(params.get("isPublic").asBoolean() ? 1 : 0);
            }
            if (params.has("tags") && params.get("tags").isArray()) {
                StringBuilder tagsBuilder = new StringBuilder();
                for (JsonNode tag : params.get("tags")) {
                    if (tagsBuilder.length() > 0) {
                        tagsBuilder.append(",");
                    }
                    tagsBuilder.append(tag.asText());
                }
                dict.setTags(tagsBuilder.toString());
            }
            
            // 如果传入了words参数，更新单词列表
            if (params.has("words") && params.get("words").isArray()) {
                JsonNode wordsNode = params.get("words");
                int wordCount = wordsNode.size();
                
                // 先删除所有旧单词
                userCustomDictWordService.deleteUserCustomDictWordByDictId(id);
                
                // 然后插入新单词
                int sortOrder = 0;
                for (JsonNode wordNode : wordsNode) {
                    UserCustomDictWord word = new UserCustomDictWord();
                    word.setDictId(id);
                    word.setWord(wordNode.get("word").asText());
                    word.setTranslation(wordNode.get("translation").asText());
                    if (wordNode.has("phonetic")) {
                        word.setPhonetic(wordNode.get("phonetic").asText());
                    }
                    if (wordNode.has("example")) {
                        word.setExample(wordNode.get("example").asText());
                    }
                    word.setSortOrder(sortOrder++);
                    userCustomDictWordService.insertUserCustomDictWord(word);
                }
                
                // 更新单词数量
                dict.setLength(wordCount);
            }
            
            return toAjax(userCustomDictService.updateUserCustomDict(dict));
        } catch (Exception e) {
            logger.error("修改自定义词典失败", e);
            return AjaxResult.error("修改失败: " + e.getMessage());
        }
    }

    /**
     * 删除自定义词典
     */
    @Log(title = "删除自定义词典", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable String id)
    {
        UserCustomDict dict = userCustomDictService.selectUserCustomDictById(id);
        if (dict == null) {
            return AjaxResult.error("词典不存在");
        }
        
        // 验证权限
        if (!dict.getUserId().equals(SecurityUtils.getUserId())) {
            return AjaxResult.error("无权删除此词典");
        }
        
        // 删除词典的所有单词
        userCustomDictWordService.deleteUserCustomDictWordByDictId(id);
        
        // 删除词典
        return toAjax(userCustomDictService.deleteUserCustomDictById(id));
    }

    /**
     * 添加单词到词典
     */
    @Log(title = "添加单词到词典", businessType = BusinessType.INSERT)
    @PostMapping("/{id}/words")
    public AjaxResult addWords(@PathVariable String id, @RequestBody JsonNode params)
    {
        try {
            UserCustomDict dict = userCustomDictService.selectUserCustomDictById(id);
            if (dict == null) {
                return AjaxResult.error("词典不存在");
            }
            
            // 验证权限
            if (!dict.getUserId().equals(SecurityUtils.getUserId())) {
                return AjaxResult.error("无权修改此词典");
            }
            
            // 获取当前最大排序号
            UserCustomDictWord query = new UserCustomDictWord();
            query.setDictId(id);
            List<UserCustomDictWord> existingWords = userCustomDictWordService.selectUserCustomDictWordList(query);
            int maxSortOrder = 0;
            for (UserCustomDictWord word : existingWords) {
                if (word.getSortOrder() != null && word.getSortOrder() > maxSortOrder) {
                    maxSortOrder = word.getSortOrder();
                }
            }
            
            // 批量插入单词
            JsonNode wordsNode = params.get("words");
            int addedCount = 0;
            for (JsonNode wordNode : wordsNode) {
                UserCustomDictWord word = new UserCustomDictWord();
                word.setDictId(id);
                word.setWord(wordNode.get("word").asText());
                word.setTranslation(wordNode.get("translation").asText());
                if (wordNode.has("phonetic")) {
                    word.setPhonetic(wordNode.get("phonetic").asText());
                }
                if (wordNode.has("example")) {
                    word.setExample(wordNode.get("example").asText());
                }
                word.setSortOrder(++maxSortOrder);
                userCustomDictWordService.insertUserCustomDictWord(word);
                addedCount++;
            }
            
            // 更新词典的单词数量
            dict.setLength((dict.getLength() != null ? dict.getLength() : 0) + addedCount);
            userCustomDictService.updateUserCustomDict(dict);
            
            return AjaxResult.success("成功添加 " + addedCount + " 个单词");
        } catch (Exception e) {
            logger.error("添加单词失败", e);
            return AjaxResult.error("添加失败: " + e.getMessage());
        }
    }

    /**
     * 更新词典单词
     */
    @Log(title = "更新词典单词", businessType = BusinessType.UPDATE)
    @PutMapping("/word/{wordId}")
    public AjaxResult editWord(@PathVariable Long wordId, @RequestBody JsonNode params)
    {
        try {
            UserCustomDictWord word = userCustomDictWordService.selectUserCustomDictWordById(wordId);
            if (word == null) {
                return AjaxResult.error("单词不存在");
            }
            
            // 验证权限
            UserCustomDict dict = userCustomDictService.selectUserCustomDictById(word.getDictId());
            if (dict == null || !dict.getUserId().equals(SecurityUtils.getUserId())) {
                return AjaxResult.error("无权修改");
            }
            
            if (params.has("word")) {
                word.setWord(params.get("word").asText());
            }
            if (params.has("translation")) {
                word.setTranslation(params.get("translation").asText());
            }
            if (params.has("phonetic")) {
                word.setPhonetic(params.get("phonetic").asText());
            }
            if (params.has("example")) {
                word.setExample(params.get("example").asText());
            }
            
            return toAjax(userCustomDictWordService.updateUserCustomDictWord(word));
        } catch (Exception e) {
            logger.error("更新单词失败", e);
            return AjaxResult.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除词典单词
     */
    @Log(title = "删除词典单词", businessType = BusinessType.DELETE)
    @DeleteMapping("/word/{wordId}")
    public AjaxResult removeWord(@PathVariable Long wordId)
    {
        UserCustomDictWord word = userCustomDictWordService.selectUserCustomDictWordById(wordId);
        if (word == null) {
            return AjaxResult.error("单词不存在");
        }
        
        // 验证权限
        UserCustomDict dict = userCustomDictService.selectUserCustomDictById(word.getDictId());
        if (dict == null || !dict.getUserId().equals(SecurityUtils.getUserId())) {
            return AjaxResult.error("无权删除");
        }
        
        int result = userCustomDictWordService.deleteUserCustomDictWordById(wordId);
        
        // 更新词典的单词数量
        if (result > 0) {
            dict.setLength((dict.getLength() != null ? dict.getLength() : 1) - 1);
            userCustomDictService.updateUserCustomDict(dict);
        }
        
        return toAjax(result);
    }

    /**
     * 导入词典（暂不实现，返回提示）
     */
    @PostMapping("/import")
    public AjaxResult importDict()
    {
        return AjaxResult.error("导入功能开发中");
    }
}

